<?php

namespace app\model;

use think\Model;

/**
 * kb_options 选项
 * @property integer $id 主键(主键)
 * @property string $name 键
 * @property mixed $value 值
 * @property integer $create_time 创建时间
 * @property integer $update_time 更新时间
 */
class Options extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'kb_options';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 更新、创建 function
     *
     * @param array $data
     * @return boolean
     */
    public static function saves(array $data): bool
    {
        foreach ($data as $key => $value) {
            $find = self::where('name', $key)->find();
            if ($find) {
                $find->value = json_encode($value, 320);
                $find->save();
            } else {
                self::create([
                    'name' => $key,
                    'value' => json_encode($value, 320)
                ]);
            }
        }
        return true;
    }

    /**
     * 获取数据 function
     *
     * @return array
     */
    public static function get(): array
    {
        $data = [];
        $options = self::select()->toArray();
        foreach ($options as $k => $v) {
            $v['value'] = json_decode($v['value'], true);
            $data[$v["name"]] = $v['value'];
        }
        return $data;
    }
}
